package com.qiniu.githubdata.service;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiniu.githubdata.entity.dto.ContributionResponse;

import java.io.IOException;

/**
 * @Author: mayixiang
 * @Date: 2024-11-03 10:54
 * @Description:
 */
@Service
public class ThirdPartyService {
    public ContributionResponse fetchGitHubContributions(String username,int year) throws IOException, ParseException {
        // URL to fetch contributions for the specified GitHub username
        String url = "https://github-contributions-api.jogruber.de/v4/" + username+"?y="+year;

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(url);
            request.addHeader("Accept", "application/json");  // Specify that we expect JSON responses

            try (CloseableHttpResponse response = httpClient.execute(request)) {
                // Check if the response status is OK (200)
                int statusCode = response.getCode();
                if (statusCode >= 200 && statusCode < 300) {
                    // Parse the response as a String
                    String jsonResponse = EntityUtils.toString(response.getEntity());
                    ObjectMapper mapper = new ObjectMapper();
                    return mapper.readValue(jsonResponse, ContributionResponse.class);
                } else {
                    throw new IOException("Unexpected response status: " + statusCode);
                }
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
//        try {
//            String contributions = fetchGitHubContributions("lionjumpma");
//            System.out.println(contributions);
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (ParseException e) {
//            throw new RuntimeException(e);
//        }
    }
}
